#include "SqliteQueryRunner.h"
#include <QDebug>
#include "Constants.h"
#include "stdlib.h"

extern "C"{
#include "sqlite/sqlite3.h"
}

SqliteQueryRunner::SqliteQueryRunner(){
}

int SqliteQueryRunner::execute(const char *sql, int (*callback)(void *, int, char **, char **), void* firstCallback, char **errmsg){
    sqlite3* db=NULL;
    int code=sqlite3_open(SQLITE_DATABASE_NAME,&db);
    if(code){
        sqlite3_close(db);
        delete db;
        db=NULL;
        return SQLITE_OPEN_DATABASE_ERROR;
    }
    qDebug()<<"SQL: "<<sql;
    code=sqlite3_exec(db,sql,callback,firstCallback,errmsg);
    sqlite3_close(db);
    delete db;
    db=NULL;
    return code;
}

int SqliteQueryRunner::query(const char *sql, char ***copy, int *pnRow, int *pnColumn, char **pzErrmsg){
    sqlite3* db=NULL;
    int code=sqlite3_open(SQLITE_DATABASE_NAME,&db);
    if(code){
        sqlite3_close(db);
        delete db;
        db=NULL;
        return SQLITE_OPEN_DATABASE_ERROR;
    }
    qDebug()<<"SQL: "<<sql;
    char** resultSet=NULL;
    code=sqlite3_get_table(db,sql,&resultSet,pnRow,pnColumn,pzErrmsg);
    if((!code)&&*pnRow>0){
        *copy=new char*[(*pnRow+1)**pnColumn];
        char* p=NULL;
        for(int i=0;i<((*pnRow+1)**pnColumn);i++){
            int size=0;
            p=resultSet[i];
            while((++size>0)&&(*p++!='\0'))
                NULL;
            const int realsize=size;
            (*copy)[i]=new char[realsize];
            strcpy((*copy)[i],resultSet[i]);
        }
    }
    sqlite3_free_table(resultSet);
    sqlite3_close(db);
    delete db;
    db=NULL;
    return code;
}
